package com.sxkiler.demo.seata.service;

import com.sxkiler.demo.seata.dto.BusinessDTO;
import com.sxkiler.demo.seata.service.saga.SAGAAccountService;
import com.sxkiler.demo.seata.service.saga.SAGABusinessService;
import com.sxkiler.demo.seata.service.saga.SAGAOrderService;
import com.sxkiler.demo.seata.service.saga.SAGAProductService;
import com.sxkiler.demo.seata.utils.IDUtils;
import io.seata.saga.engine.StateMachineEngine;
import io.seata.saga.statelang.domain.ExecutionStatus;
import io.seata.saga.statelang.domain.StateMachineInstance;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SAGABusinessServiceImpl implements SAGABusinessService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Reference(id="sagaProductService")
    SAGAProductService productService;
    @Reference(id="sagaAccountService")
    SAGAAccountService accountService;
    @Reference(id="sagaOrderService")
    SAGAOrderService orderService;


    @Autowired
    StateMachineEngine stateMachineEngine;

    @Override
    public String handlerBusiness(BusinessDTO businessDTO) {
        logger.info("[handleBusiness] 开始下单, 订单详情: {}", businessDTO.toString());

        // 查询 商品单价
        Integer price = productService.getPriceById(businessDTO.getProductId());
        Integer payAmount = price * businessDTO.getCount();
        logger.info("[handleBusiness] 订单总价格: {}", payAmount);

        // 生成订单 ID
        Long orderId = IDUtils.nextId();

        Map<String, Object> businessParam = new HashMap<>();
        businessParam.put("orderId", orderId);
        businessParam.put("userId", businessDTO.getUserId());
        businessParam.put("productId", businessDTO.getProductId());
        businessParam.put("count", businessDTO.getCount());
        businessParam.put("amount", payAmount);

        StateMachineInstance instance = stateMachineEngine.start("DesignerBusinessOrder", null, businessParam);
        if(ExecutionStatus.SU.equals(instance.getStatus())) {
            logger.info("[handleBusiness] 下单成功, 响应结果: {} ", instance.getStatus().getStatusString());
        } else {
            logger.error("[handleBusiness] 下单失败, 响应结果: {} ", instance.getStatus().getStatusString());
        }
        return instance.getStatus().getStatusString();
    }
}
